<template>
  <div class="AI_creating">
    <!-- 头部 -->
    <div class="ai_header">
      <img src="@/assets/images/ic_back@2x.png" @click="backRouter" />
      <span class="ai_title">AI Pose</span>
    </div>
    <!-- 正常走进度条流程 -->
    <div v-if="generateStaus">
      <div class="wrap_defual_cover">
        <img :src="poseCoverImg" />
      </div>
      <div class="ai_tips">
        <div class="top_tips">AI is creating……</div>
        <div class="progress-container">
          <!-- 百分比显示 -->
          <div class="progress-text">{{ progress }}%</div>
          <!-- 进度条 -->
          <div class="progress-bar-background">
            <div class="progress-bar-filled" :style="{ width: progress + '%', backgroundColor: '#6251FF' }"></div>
          </div>
        </div>
        <div class="bottom_tips">The AI will notify you when the <br />image is finished</div>
      </div>
      <div class="ai_button" @click="btnClick">Check lt Out In My Works Later</div>
    </div>
    <div class="loading_box" v-if="loadingStatus">
      <div class="inner_box">
        <div class="processing_tip" style="margin-bottom: 16px;">It will be ready soon. Please wait a moment.</div>
        <van-loading type="spinner" color="#1989fa" />
        <div class="processing_tip">Processing your image...</div>
      </div>
    </div>
    <!-- 生成完成后，展示如下结果，可以继续 go 生成 -->
    <div class="generate_result" v-if="showResult">
      <div class="img_wrap" @comfrim="removeBlur">
        <img :src="resultFileUrl || pollResult.resultFileUrl"
          :style="hasPaid ? {} : { filter: 'blur(5px)', transition: 'filter 0.5s' }" />
      </div>
      <!-- 确认提交按钮 -->
      <!-- 没有充值的用户显示这个按钮，如果已经充值的用户，就直接结果显示 -->
      <div class="comfirm_btn_wrap" v-if="!hasPaid">
        <ComfirmBtn btnName="Remove Blur" :gemsNum="gemsNum" :diamondNum="diamondNum" :isShowDiamond="isShowDiamond"
          @comfrim="removeBlur" />
      </div>
      <!-- 结果展示页 -->
      <div class="show_reasult">
        <div style="font-size: 16px;color: #333;">More AI poses</div>
        <ResultList @goNext="goNext" />
      </div>
    </div>
    <!-- 钻石消耗 -->
    <van-popup v-model:show="useDiamondShow" class="user_diamonds">
      <div class="title">You have consumed the gems</div>
      <div class="bottm_block">
        <img src="@/assets/images/ic_star_64@2x.png" />
        <span class="number">x100</span>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import router from "@/router";
import ResultList from "@/components/ResultList.vue";
import api from "@/api";
import { usePollingStore } from "@/stores/polling";
import { useRoute } from "vue-router";
import { trackEvent } from "@/utils/firebase";
import { showConfirmDialog } from "vant";
import { compressImageUrl } from "@/utils/imageCompress";

const route = useRoute();

// 轮询
const store = usePollingStore();
// 动态获取任务结果
const pollResult = computed(() => {
  const taskNo = route.query.taskNo;
  if (!taskNo)
    return {
      resultFileUrl: "",
      isPolling: false,
      isPollFail: false,
    };

  const taskState = store.getTaskResult(taskNo);

  return taskState
    ? {
      resultFileUrl: taskState.imgUrl,
      isPolling: !!store.pollingTasks.get(taskNo)?.isPolling,
      isPollFail: taskState.isPollFail,
    }
    : {
      resultFileUrl: "",
      isPolling: false,
      isPollFail: false,
    };
});

// 监听任务完成状态
watch(
  () => pollResult.value.isPolling,
  (isPolling) => {
    if (!isPolling && pollResult.value.resultFileUrl) {
      console.log("任务完成，图片地址:", pollResult.value.resultFileUrl);
      // 这里可以执行图片加载后的逻辑
    }
  }
);
// 进入页面查询到的结果
const resultFileUrl = ref("");

const useDiamondShow = ref(false);
const generateStaus = ref(false);
const loadingStatus = ref(false);
const showResult = ref(false);

// 该用户是否已经充值
const hasPaid = ref(false);

const gemsNum = ref("");
const diamondNum = ref("100");
const isShowDiamond = ref(true);

const poseCoverImg = ref("");

const backRouter = () => {
  showConfirmDialog({
    confirmButtonText: "back",
    className: "custom-delete-dialog",
    cancelButtonText: "Cancel",
    message: "Are you sure you want to back?",
  })
    .then(() => {
      router.back();
    })
    .catch(() => {
      // on cancel
    });
};


const removeBlur = () => {
  // 点击按钮，钻石充足，执行工作流
  if (Number(gemsNum.value) >= 100) {
    // 扣除100钻石，显示清晰的图片
    gemsNum.value = String(Number(gemsNum.value) - 100);
    // 显示
    hasPaid.value = true;
  } else {
    //钻石不足，跳往充值有页
    router.push("./myDiamonds");
  }
  trackEvent('生成结果页_点击【Remove Blur】', { id: '100044' });
};

// 点击go前往
const goNext = () => {
  // 点击跳转前，必须已经有oss返回的图片地址
  router.push("./AIPose");
};

const progress = ref(0); // 当前进度（0-100）
// 模拟进度
const simulateProgress = () => {
  const duration = 10000; // 6秒
  const interval = 100; // 更新间隔（越小越平滑）
  const steps = duration / interval;
  const increment = 100 / steps;
  let step = 0;
  const timer = setInterval(() => {
    if (step >= steps) {
      clearInterval(timer);
      progress.value = 100; // 确保结束时精确到100%
      // 弹出钻石消耗
      useDiamondShow.value = true;
      setTimeout(() => {
        useDiamondShow.value = false;
      }, 3000);
      // 进度条执行完成，展示结果；清空 sessionStorage 存值，放置刷新
      generateStaus.value = false;
      loadingStatus.value = false;
      showResult.value = true;
      //sessionStorage.setItem("poseFinish", true);//生成图片成功，用于在当前页面刷新重新调起进度条
      trackEvent("执行工作流成功_展示生成结果", { id: "100043" }); //埋点
    } else {
      if (pollResult.value.isPollFail) {
        // 判断是否错误重试
        store.stopPolling(route.query.taskNo); // 组件卸载时强制停止
        // 跳到/retryPage 页面，再将 isPollFail 设为 false，不然会进入else逻辑，错误执行 step++
        // store.isPollFail = false;
        router.push({
          path: "/retryPage",
          query: {
            taskNo: route.query.taskNo,
            from: "pose",
          },
        });
      } else if (progress.value === 99 && pollResult.value.isPolling) {
        //判断是否轮询回结果
        generateStaus.value = false; //隐藏进度条
        loadingStatus.value = true; //显示加载框
        return true;
      } else {
        progress.value += increment;
        step++;
      }
    }
  }, interval);
  trackEvent("执行工作流（开始制作)", { id: "100041" }); //埋点
};

// 点击回到首页
const btnClick = () => {
  trackEvent("执行工作流界面_点击【Check lt Out In My Works Later】", { id: "100042" }); //埋点
  router.push("./");
};

// 用户信息
const getUseInfo = async () => {
  try {
    const response = await api.userInfo();
    gemsNum.value = response.data.balance;
    if (response.data.rechargeStatus === 1) {
      //是否支付
      hasPaid.value = true;
    } else {
      hasPaid.value = false;
    }
  } catch (err) {
    console.log(err);
  }
};

// 查询任务详情
const queryTaskInfo = async () => {
  try {
    const res = await api.taskInfo({ taskNo: route.query.taskNo });
    if (res?.data?.resultFileUrl) {
      store.stopPolling(route.query.taskNo); // 停止旧轮询
      showResult.value = true;
      resultFileUrl.value = await compressImageUrl(res.data.resultFileUrl); //压缩返回的图片
    } else {
      // 如果查询不到结果，才进行creating逻辑
      generateStaus.value = true; // 显示进度条页面
      simulateProgress(); // 执行进度条
      store.startPolling({ taskNo: route.query.taskNo }); // 执行轮询
    }
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  // 如果是其他页面跳到这个页面，需要显示进度条执行的页面；如果是在当前页面刷新，则显示结果显示页面
  if (route.query.from && route.query.taskNo) {
    // 进入页面，先调taskInfo接口，查询，看在这个taskNo下，是否已经有结果；如果有，就展示结果页，如果没有，才会执行进度条生成
    queryTaskInfo();
  }
  // 获取用户信息
  getUseInfo();
  //获取图片
  poseCoverImg.value = sessionStorage.getItem("aiposeCover");
  // 卸载时
  onUnmounted(() => {
    //store.stopPolling(); // 组件卸载时强制停止
    const taskNo = route.query.taskNo;
    if (taskNo) {
      // 清理该任务的完成状态
      store.completedTasks.delete(taskNo);

      // 如果这个任务是最新完成的任务，清除它
      if (store.latestCompletedTask?.taskNo === taskNo) {
        store.clearLatestCompletedTask();
      }
    }
  });
});
</script>

<style scoped lang="less">
.AI_creating {
  width: 100%;
  box-sizing: border-box;
  padding: 0 16px;
  min-height: 100vh;
  /* 背景图设置 */
  background-image: url("../assets/images/bg_texture@2x.png");
  background-position: top center;
  /* 从顶部开始 */
  background-repeat: no-repeat;
  /* 不重复 */
  background-size: 100% auto;
  /* 宽度满屏，高度自适应 */
  background-color: #fbfbfd;
  padding-bottom: 56px;

  .wrap_defual_cover {
    width: 100%;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      max-width: 100%;
      /* 限制最大宽度为容器宽度 */
      max-height: 100%;
      /* 限制最大高度为容器高度 */
      width: auto;
      /* 保持原始宽度比例 */
      height: auto;
      /* 保持原始高度比例 */
      object-fit: contain;
      /* 保持比例，完整显示图片 */
    }
  }

  .ai_header {
    height: 56px;
    display: flex;
    position: relative;
    line-height: 56px;

    img {
      width: 24px;
      position: absolute;
      left: 0px;
      top: 16px;
    }

    .ai_title {
      font-size: 18px;
      font-weight: 700;
      margin-left: 46px;
    }
  }

  .loading_box {
    width: 100%;
    height: calc(100vh - 150px);
    margin-top: 12px;
    padding: 3px;
    border: 1.06667vw solid;
    border-image: linear-gradient(90deg, rgba(255, 213, 47, 1), rgba(248, 116, 255, 1), rgba(81, 110, 255, 1)) 4 4;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    overflow: hidden;

    .inner_box {
      width: 100%;
      height: 100%;
      border-radius: 10px;
      background: #ffffff;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
    }

    .processing_tip {
      text-align: center;
      font-size: 13px;
      margin-top: 12px;
    }
  }

  .generate_result {

    /* 设置模糊效果 */
    :deep(.blur-image) {
      filter: blur(5px);
      transition: filter 0.5s;
    }

    .img_wrap {
      border: 1.06667vw solid;
      border-image: linear-gradient(90deg, rgba(255, 213, 47, 1), rgba(248, 116, 255, 1), rgba(81, 110, 255, 1)) 4 4;
      width: 100%;
      height: 300px;
      margin-top: 16px;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        max-width: 100%;
        /* 限制最大宽度为容器宽度 */
        max-height: 100%;
        /* 限制最大高度为容器高度 */
        width: auto;
        /* 保持原始宽度比例 */
        height: auto;
        /* 保持原始高度比例 */
        object-fit: contain;
        /* 保持比例，完整显示图片 */
      }
    }
  }

  .comfirm_btn_wrap {
    margin-top: 50px;
  }

  .wrap_img {
    margin-top: 16px;

    img {
      width: 100%;
    }
  }

  .ai_tips {
    text-align: center;

    .top_tips {
      height: 19px;
      line-height: 19px;
      font-weight: 400;
      font-size: 16px;
      color: #000000;
      text-align: center;
      margin-top: 16px;
      margin-bottom: 8px;
    }

    .bottom_tips {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      text-align: center;
    }
  }

  .ai_button {
    text-align: center;
    width: 312px;
    margin: 0 auto;
    margin-top: 25px;
    height: 64px;
    line-height: 64px;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(0, 0, 0, 0.45);
    font-weight: 400;
    font-size: 18px;
    color: #000000;
  }

  .show_reasult {
    margin-top: 60px;
  }

  .user_diamonds {
    width: 280px;
    height: 150px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .title {
      font-size: 18px;
      color: #000000;
      text-align: center;
      margin-bottom: 24px;
    }

    .bottm_block {
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        width: 55px;
      }

      .number {
        font-size: 28px;
        color: #000000;
        margin-left: 8px;
      }
    }
  }
}

.progress-container {
  position: relative;
  width: 100%;
  margin-top: 96px;
  margin-bottom: 12px;
}

.progress-text {
  position: absolute;
  top: -96px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 64px;
  color: #000000;
  font-weight: bold;
}

.progress-bar-background {
  width: 232px;
  height: 8px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.1);
  /* 未执行部分灰色 */
  //border-radius: 6px;
  overflow: hidden;
}

.progress-bar-filled {
  height: 100%;
  //border-radius: 6px;
  transition: width 0.3s ease;
  /* 平滑过渡效果 */
}
</style>
